<template>
  <view class="demo-container">
    <view class="demo-header">
      <text class="demo-title">图片框选组件演示</text>
    </view>
    
    <!-- 图片框选组件 -->
    <ImageSelector
      v-if="demoImage"
      :imageUrl="demoImage"
      :coordinates="coordinates"
      :width="containerWidth"
      :height="containerHeight"
      :rotation="rotation"
      @ready="onSelectorReady"
      @coordinatesChange="onCoordinatesChange"
      @dragStart="onDragStart"
      @dragEnd="onDragEnd"
      @resize="onResize"
      @add="onAddBox"
      @delete="onDeleteBox"
      @error="onError"
    />
    
    <!-- 控制面板 -->
    <view class="control-panel">
      <button class="control-btn" @tap="selectImage">选择图片</button>
      <button class="control-btn" @tap="rotateImage">旋转 ({{ rotation }}°)</button>
      <button class="control-btn" @tap="clearBoxes">清空框选</button>
      <button class="control-btn" @tap="showCoordinates">显示坐标</button>
    </view>
    
    <!-- 状态显示 -->
    <view class="status-panel">
      <text class="status-text">框选框数量: {{ coordinates.length }}</text>
      <text class="status-text">当前状态: {{ currentStatus }}</text>
    </view>
  </view>
</template>

<script>
import ImageSelector from '@/components/ImageSelector/index.vue';

export default {
  components: {
    ImageSelector
  },
  
  data() {
    return {
      demoImage: '',
      coordinates: [
        {
          id: 'demo1',
          x: 0.1,
          y: 0.1,
          width: 0.3,
          height: 0.2
        },
        {
          id: 'demo2',
          x: 0.5,
          y: 0.4,
          width: 0.25,
          height: 0.3
        }
      ],
      rotation: 0,
      containerWidth: 375,
      containerHeight: 500,
      currentStatus: '准备中',
      selectorRef: null
    };
  },
  
  onReady() {
    // 获取容器尺寸
    this.getContainerSize();
    
    // 加载默认图片
    this.loadDefaultImage();
  },
  
  methods: {
    // 获取容器尺寸
    getContainerSize() {
      const systemInfo = uni.getSystemInfoSync();
      this.containerWidth = systemInfo.windowWidth - 40;
      this.containerHeight = systemInfo.windowHeight - 200;
    },
    
    // 加载默认图片
    loadDefaultImage() {
      // 使用一个简单的base64图片作为演示
      this.demoImage = '';
    },
    
    // 选择图片
    selectImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempPath = res.tempFilePaths[0];
          
          // H5平台需要特殊处理
          // #ifdef H5
          this.convertImageToBase64(tempPath);
          // #endif
          
          // 非H5平台直接使用
          // #ifndef H5
          this.demoImage = tempPath;
          this.currentStatus = '图片已更换';
          // #endif
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'error'
          });
        }
      });
    },
    
    // 将图片转换为base64 (H5平台使用)
    convertImageToBase64(imagePath) {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      const img = new Image();
      
      img.crossOrigin = 'anonymous';
      img.onload = () => {
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        ctx.drawImage(img, 0, 0);
        
        const base64 = canvas.toDataURL('image/jpeg', 0.8);
        this.demoImage = base64;
        this.currentStatus = '图片已更换';
      };
      
      img.onerror = (error) => {
        console.error('图片加载失败:', error);
        this.currentStatus = '图片处理失败';
        uni.showToast({
          title: '图片处理失败',
          icon: 'error'
        });
      };
      
      img.src = imagePath;
    },
    
    // 旋转图片
    rotateImage() {
      this.rotation = (this.rotation + 90) % 360;
      this.currentStatus = `已旋转到 ${this.rotation}°`;
    },
    
    // 清空框选
    clearBoxes() {
      this.coordinates = [];
      this.currentStatus = '已清空所有框选框';
    },
    
    // 显示坐标
    showCoordinates() {
      const coordText = JSON.stringify(this.coordinates, null, 2);
      uni.showModal({
        title: '当前坐标数据',
        content: coordText,
        showCancel: false
      });
    },
    
    // 框选组件事件处理
    onSelectorReady() {
      this.currentStatus = '组件已就绪';
      console.log('图片框选组件已就绪');
    },
    
    onCoordinatesChange(coordinates) {
      this.coordinates = coordinates;
      this.currentStatus = '坐标已更新';
      console.log('坐标更新:', coordinates);
    },
    
    onDragStart(boxId) {
      this.currentStatus = `拖拽开始: ${boxId}`;
      console.log('拖拽开始:', boxId);
    },
    
    onDragEnd(boxId) {
      this.currentStatus = `拖拽结束: ${boxId}`;
      console.log('拖拽结束:', boxId);
    },
    
    onResize(boxId) {
      this.currentStatus = `调整大小: ${boxId}`;
      console.log('调整大小:', boxId);
    },
    
    onAddBox(coordinate) {
      this.currentStatus = `新增框选框: ${coordinate.id}`;
      console.log('新增框选框:', coordinate);
    },
    
    onDeleteBox(boxId) {
      this.currentStatus = `删除框选框: ${boxId}`;
      console.log('删除框选框:', boxId);
    },
    
    onError(error) {
      this.currentStatus = '组件错误';
      console.error('组件错误:', error);
      uni.showToast({
        title: '组件错误',
        icon: 'error'
      });
    }
  }
};
</script>

<style scoped>
.demo-container {
  min-height: 100vh;
  background: #1a1a1a;
  color: #ffffff;
  padding: 20px;
}

.demo-header {
  text-align: center;
  margin-bottom: 20px;
}

.demo-title {
  font-size: 20px;
  font-weight: 600;
  color: #ffffff;
}

.control-panel {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 20px 0;
}

.control-btn {
  flex: 1;
  min-width: 80px;
  height: 40px;
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
}

.control-btn:active {
  background: #0056b3;
}

.status-panel {
  background: #2c2c2c;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
}

.status-text {
  display: block;
  color: #ffffff;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 5px;
}

.status-text:last-child {
  margin-bottom: 0;
}
</style>
